import requests
from requests.exceptions import ConnectionError
from config.config import load_config
from db.etcd import EtcdClient
from db.redis import RedisClient

# Load configurations
fnsa_inference_config, etcd_host, etcd_port, redis_host, redis_port, redis_db = load_config()

# Initialize ETCD and Redis clients
etcd_client = EtcdClient(host=etcd_host, port=etcd_port)
redis_client = RedisClient(host=redis_host, port=redis_port, db=redis_db)

def analyze_sentiment(text):
    url = fnsa_inference_config.analyze_sentiment_uri
    payload = {
        "inputs": [
            {
                "name": "input",
                "shape": [1],
                "datatype": "BYTES",
                "data": [text]
            }
        ]
    }
    headers = {
        'Content-Type': 'application/json'
    }
    response = requests.post(url, json=payload, headers=headers)
    response_data = response.json()
    
    if 'outputs' not in response_data:
        raise ValueError(f"Unexpected response format: {response_data}")
    
    return response_data

def check_mlserver_connection():
    url = fnsa_inference_config.analyze_sentiment_uri
    try:
        response = requests.get(url, timeout=5)
        response.raise_for_status()
        return True
    except (ConnectionError, requests.exceptions.HTTPError) as e:
        return False

def get_feeds(client_type='etcd'):
    if client_type == 'etcd':
        return etcd_client.get_prefix('/feeds/')
    elif client_type == 'redis':
        return redis_client.get_prefix('/feeds/')
    else:
        raise ValueError("Invalid client type. Use 'etcd' or 'redis'.")
